package dbs

import (
	"fmt"
	"go.uber.org/zap"
	"gobase/logger"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/plugin/dbresolver"
)

func InitMysql() {
	var err error
	if conf.MultiDB {
		var master *DbInfo
		var silver []*DbInfo
		for _, info := range conf.DBs {
			if info.DBType == "master" {
				master = &info
			}
			if info.DBType == "silver" {
				silver = append(silver, &info)
			}
		}
		if master == nil {
			logger.Error("Multi DB No Master")
			return
		}
		if len(silver) == 0 {
			logger.Error("Multi DB No Silver")
		}

		if master.CharSet == "" {
			master.CharSet = "utf8"
		}
		db, err = gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local", master.User, master.Password, master.Addr, master.Port, master.DbName, master.CharSet)), &gorm.Config{})
		if err != nil {
			logger.Error("Init Mysql Master DB error", zap.Error(err))
			return
		}
		var dialector []gorm.Dialector
		for _, info := range silver {
			dialector = append(dialector, mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local", info.User, info.Password, info.Addr, info.Port, info.DbName, info.CharSet)))
		}
		if err := db.Use(dbresolver.Register(dbresolver.Config{Replicas: dialector})); err != nil {
			logger.Error("Init Mysql Silver DB error", zap.Error(err))
			return
		}
	} else {
		cfg := conf.DBs[0]
		if cfg.CharSet == "" {
			cfg.CharSet = "utf8"
		}
		db, err = gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local", cfg.User, cfg.Password, cfg.Addr, cfg.Port, cfg.DbName, cfg.CharSet)), &gorm.Config{})
		if err != nil {
			logger.Error("Init Mysql DB error", zap.Error(err))
			return
		}
	}
	p, err := db.DB()
	if err != nil {
		logger.Error("Mysql DB conn error", zap.Error(err))
		return
	}
	p.SetMaxIdleConns(conf.MaxIdleConns)
	p.SetMaxOpenConns(conf.MaxOpenConns)
	if conf.Debug {
		db.Debug()
	}
}
